﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls.Primitives;
using System.Windows.Controls;

namespace ViewMaker.Core.Wpf
{
    public static class EnterKeyBehavior
    {
        public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(EnterKeyBehavior), new PropertyMetadata(CommandCallback));

        public static ICommand GetCommand(FrameworkElement obj)
        {
            return (ICommand)obj.GetValue(CommandProperty);
        }

        public static void SetCommand(FrameworkElement obj, ICommand value)
        {
            obj.SetValue(CommandProperty, value);
        }

        private static void CommandCallback(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            var ele = obj as FrameworkElement;
            if (ele != null)
            {
                if (args.OldValue == null && args.NewValue != null)
                {
                    ele.PreviewKeyDown += new KeyEventHandler(ElementKeyDown);
                }
                else if (args.OldValue != null && args.NewValue == null)
                {
                    ele.PreviewKeyDown -= new KeyEventHandler(ElementKeyDown);
                }
            }
        }

        static void ElementKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Enter) return;
            var txt = e.OriginalSource as TextBox;
            if (txt != null)
            {
                var be = txt.GetBindingExpression(TextBox.TextProperty);
                if (be != null) be.UpdateSource();
            }
            var ele = e.OriginalSource as FrameworkElement;
            ICommand cmd = (ICommand)ele.GetValue(CommandProperty);
            if (cmd != null) cmd.Execute(null);
        }
    }
}
